// pages/comment/comment.js
const app = getApp()
import api from '../../utils/api'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        navBarHeight: app.globalData.navBarHeight, //导航栏高度
        menuBotton: app.globalData.menuBotton, //导航栏距离顶部距离
        menuHeight: app.globalData.menuHeight, //导航栏高度
        dish_id: "",
        foodName: "",
        foodImg: '',
        canteenName: "",
        foodTime: "",
        foodDiscription: "",
        foodDetail: [],
        price: '',
        comment: "",
        foodComments: [],
        firstDay: "",
        inputVal: "",
        voteType: 0,  // 0-默认，1-喜欢，2-讨厌
        isVote: false,
        imgUrl: '',
        imgName: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // console.log(options)
        wx.hideShareMenu()
        //菜品信息
        this.setData({
            foodName: options.foodName,
            foodImg: options.imgUrl,
            canteenName: options.canteen,
            foodTime: options.meal == 0 ? '早餐' : options.meal == 1 ? '午餐' : options.meal == 2 ? '晚餐' : '',
            foodDiscription: options.description,
            foodDetail: options.description.split('/'),
            // price: options.price == '--' ? '--' : options.price + '.00',
            price: options.price == '--' ? '--' : options.price,
            dish_id: options.dish_id,
            firstDay: options.firstDay
        })

        //首次加载请求默认评论
        // this.requestBenYue()
        //2021年7月20日16:24:09修改为只显示全部评论，首次加载
        this.requestQuanBu();
        this.getDishStatus ()
    },

    getDishStatus: function () {
        let data = {
            workNo: wx.getStorageSync('workNo'),
            canteenid: JSON.parse(wx.getStorageSync('voteData')).canteenid,
            menuDate: JSON.parse(wx.getStorageSync('voteData')).menuDate,
            dishID: JSON.parse(wx.getStorageSync('voteData')).dishID
        }
        wx.request({
            url: api.getDishStatus,
            method: "POST",
            data: data,
            header: {
                'content-type': 'application/json',
                'token': wx.getStorageSync('token')
            },
            success: res => {
                if (res.data.state == 1) {
                    this.setData({ voteType: res.data.data.voteType })
                }
            }
        })
    },

    showVote: function () {
        if (this.data.canteenName == '江茂源') return;
        let isVote = this.data.isVote
        this.setData({
            isVote: !isVote
        })
    },

    voteTab: function (e) {
        let voteData = JSON.parse(wx.getStorageSync('voteData'))
        voteData.workNo = wx.getStorageSync('workNo')
        voteData.voteType = e.currentTarget.dataset.type
        wx.request({
            url: api.vote,
            method: "POST",
            data: voteData,
            header: {
                'content-type': 'application/json',
                'token': wx.getStorageSync('token')
            },
            success: res => {
                if (res.data.state == 1) {
                    this.setData({ 
                        voteType: e.currentTarget.dataset.type,
                        isVote: false 
                    })
                }
            }
        })
    },

    // 上传图片
    uploadImg: function (e) {
        if (this.data.canteenName == '江茂源') return;
        wx.chooseImage({
            count: 1,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                let imgUrl = res.tempFilePaths;
                //显示等待框
                wx.showLoading({
                    title: '图片上传中',
                })
                //调取图片上传
                wx.uploadFile({
                  filePath: res.tempFilePaths[0],
                  name: 'img',
                  url: api.uploadImg,
                  success: (res) => {
                    wx.hideLoading()
                    var data = JSON.parse(res.data)
                    if (data.state == 1) {
                      wx.showToast({
                        title: '图片上传成功',
                      })
                      this.setData({
                        //   imgUrl: data.data.imgUrl
                        imgUrl: imgUrl[0],
                        imgName: data.data.imgName
                      })
                    } else if (data.state == "2") {
                      wx.showToast({
                        title: '图片上传失败',
                      })
                    }
                  },
                  fail: function (err) {
                    wx.showToast({
                        title: '图片上传失败',
                    })
                  },
                  complete: () => {
                    // console.log("complete")
                  }
                })
            }
        })
    },

    // 删除图片
    deleteImg: function (e) {
        this.setData({
            imgUrl: ''
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    commentInput: function (e) {
        this.setData({
            comment: e.detail.value
        })
    },

    sendClick: function (e) {
        if (this.data.canteenName == '江茂源') return;
        var dish_id = parseInt(this.data.dish_id)
        var that = this
        if (this.data.comment == "") {
            wx.showToast({
                title: '请输入评论',
            })
        } else {
            wx.request({
                // url: 'https://542124141.xyz/pam/comment/add',
                url: api.sendComment,
                method: "POST",
                data: {
                    dish_id: dish_id,
                    comment: that.data.comment,
                    imgName: that.data.imgName
                },
                header: {
                    // 'content-type': 'application/x-www-form-urlencoded',
                    'content-type': 'application/json',
                    'token': wx.getStorageSync('token')
                },
                success(e) {
                    if (e.statusCode == 200) {
                        wx.showToast({
                            title: '评论成功！',
                        })
                        that.setData({
                            inputVal: "",
                            comment: "",
                            imgUrl: ''

                        })
                        that.requestBenYue()
                    } else {
                        wx.showToast({
                            title: '评论失败'+e.statusCode,
                        })
                    }
                }
            })
        }
    },
    requestBenYue: function (e) {
        var that = this
        //清除数据
        this.setData({
            foodComments: new Array
        })
        //请求评论
        wx.request({
            // url: "http://124.207.4.211:8008/pam/comment/getList?dish_id=" + this.data.dish_id + "&begin_date=" + this.data.firstDay + "&pageSize=999",
            //  url: "https://542124141.xyz/pam/comment/getList?dish_id=" + this.data.dish_id + "&begin_date=" + this.data.firstDay + "&pageSize=999",
            url: api.getComment + "?dish_id=" + this.data.dish_id + "&begin_date=" + this.data.firstDay + "&pageSize=999",
            method: "GET",
            success(res) {
                for (var i = 0; i < res.data.data.total; i++) {
                    var userName = res.data.data.list[i].user_id
                    var commentText = res.data.data.list[i].comment
                    var commentTime = res.data.data.list[i].comment_time
                    var replyName = "新中物业/园区管理办公室"
                    var replyText = res.data.data.list[i].reply
                    var replyTime = res.data.data.list[i].reply_time
                    let imgUrl = res.data.data.list[i].imgUrl
                    var tmp = {
                        userName,
                        commentTime,
                        commentText,
                        replyName,
                        replyTime,
                        replyText,
                        imgUrl
                    }


                    that.data.foodComments.push(tmp)
                }

                that.setData({
                    foodComments: that.data.foodComments
                })
            }
        })
    },
    requestQuanBu: function (e) {
        var that = this
        //清除数据
        this.setData({
            foodComments: new Array
        })
        //请求评论
        wx.request({

            // url: "http://124.207.4.211:8008/pam/comment/getList?dish_id=" + this.data.dish_id + "&begin_date=2000-01-01&pageSize=999",
            // url: "https://542124141.xyz/pam/comment/getList?dish_id=" + this.data.dish_id + "&begin_date=2000-01-01&pageSize=999",
            url: api.getComment + "?dish_id=" + this.data.dish_id + "&begin_date=2000-01-01&pageSize=999",

            method: "GET",
            success(res) {
                for (var i = 0; i < res.data.data.total; i++) {
                    var userName = res.data.data.list[i].user_id
                    var commentText = res.data.data.list[i].comment
                    var commentTime = res.data.data.list[i].comment_time
                    var replyName = "新中物业/园区管理办公室"
                    var replyText = res.data.data.list[i].reply
                    var replyTime = res.data.data.list[i].reply_time
                    var tmp = {
                        userName,
                        commentTime,
                        commentText,
                        replyName,
                        replyTime,
                        replyText,
                    }
                    that.data.foodComments.push(tmp)
                }

                that.setData({
                    foodComments: that.data.foodComments
                })
            }
        })
    },
    benYue: function (e) {
        this.requestBenYue()
    },
    quanBu: function (e) {
        this.requestQuanBu()
    },
    // 返回上一层
    goBack: function (e) {
        wx.navigateBack({
        delta: 1,
        })
    },
    //点击放大图片
previewPic: function (e) {
    var imgUrls = []
      imgUrls = [this.data.foodImg]
    wx.previewImage({
      urls: imgUrls, //需要预览的图片http链接列表，注意是数组
      current: '', // 当前显示图片的http链接，默认是第一个
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  
  },
})